package com.macro.mall.portal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.enums.DelFlagEnums;
import com.macro.mall.common.enums.SitQuietlyClockFieldEnum;
import com.macro.mall.dto.applet.*;
import com.macro.mall.mapper.SitQuietlyClockMapper;
import com.macro.mall.model.SitQuietlyClock;
import com.macro.mall.model.SitQuietlyClockExample;
import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.service.MemberClockService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.vo.applet.AppletMemberSignVO;
import com.macro.mall.vo.applet.AppletRankVO;
import com.macro.mall.vo.applet.AppletStatsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author xq
 * @description MemberClockServiceImpl
 * @date 2024/2/23 14:46
 */
@Slf4j
@Service(value = "memberClockService")
public class MemberClockServiceImpl implements MemberClockService {
    @Resource
    private SitQuietlyClockMapper sitQuietlyClockMapper;

    private Integer deadLineTime = 15;

    @Resource
    private UmsMemberService umsMemberService;

    @Override
    public AppletMemberSignVO signList(QuerySignListDTO queryDto) {
        AppletMemberSignVO signVO = new AppletMemberSignVO();
        SitQuietlyClockExample countExample = new SitQuietlyClockExample();
        countExample.createCriteria().andUserIdEqualTo(queryDto.getMemberId()).andTypeEqualTo(1);
        signVO.setSignCount(sitQuietlyClockMapper.countByExample(countExample));
        signVO.setSignInfoVOList(this.sitQuietlyClockMapper.signList(queryDto));
        signVO.setIntegralNum(0);
        return signVO;

    }

    @Override
    public CommonResult sign(AppletSignDTO req) {
        Long dateNo = Long.valueOf(DateUtil.format(req.getDate(), DatePattern.PURE_DATE_FORMATTER));
        // 签到只能签到今天
        Long nowDateNo = Long.valueOf(DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_FORMATTER));
        // 补卡只能补昨天的卡
        long num = DateUtil.betweenDay(req.getDate(), DateUtil.date(), true);
        if (num > 1) {
            return CommonResult.failed("补卡只能补昨天！");
        }
        SitQuietlyClockExample kuangExample = new SitQuietlyClockExample();
        kuangExample.createCriteria().andUserIdEqualTo(req.getMemberId()).andTypeEqualTo(3).andDateNoEqualTo(dateNo);
        long kuanNum = sitQuietlyClockMapper.countByExample(kuangExample);
        if (kuanNum > 0) {
            return CommonResult.failed("该天已旷卡！");
        }
        SitQuietlyClockExample applyExample = new SitQuietlyClockExample();
        applyExample.createCriteria().andUserIdEqualTo(req.getMemberId()).
                andTypeEqualTo(2).andDateNoEqualTo(dateNo);
        long applyNum = sitQuietlyClockMapper.countByExample(applyExample);
        if (applyNum > 0) {
            List<SitQuietlyClock> sitQuietlyClocks = sitQuietlyClockMapper.selectByExample(applyExample);
            SitQuietlyClock sitQuietlyClock1 = sitQuietlyClocks.get(0);
            // 如果当天请假了，但是后面又打卡了，则可以进行修改
            // 获取当前的时间分钟
            SitQuietlyClock sitQuietlyClock = new SitQuietlyClock();
            sitQuietlyClock.setId(sitQuietlyClock1.getId());
            sitQuietlyClock.setType(1);
            sitQuietlyClock.setStartTime(DateUtil.offsetMinute(DateUtil.date(), -req.getTimeInterval()));
            sitQuietlyClock.setEndTime(DateUtil.date());
            sitQuietlyClock.setSignDate(DateUtil.format(req.getDate(), DatePattern.NORM_DATE_PATTERN));
            sitQuietlyClock.setTimeInterval(req.getTimeInterval());
            sitQuietlyClock.setModifyTime(DateUtil.date());
            sitQuietlyClockMapper.updateByPrimaryKeySelective(sitQuietlyClock);
            return CommonResult.success(1);
        }
        SitQuietlyClockExample countExample = new SitQuietlyClockExample();
        countExample.createCriteria().andUserIdEqualTo(req.getMemberId()).andTypeEqualTo(1).andDateNoEqualTo(dateNo);
        long signNum = sitQuietlyClockMapper.countByExample(countExample);
        if (signNum > 0) {
            return CommonResult.failed("该天已打卡！");
        }
        // 补昨天的卡，今天3点以后就不能补
        // 如果当前时间小于现在
        if (dateNo < nowDateNo) {
            // 判断当前时间是否 大于下午3点
            int currentHour = DateUtil.hour(DateUtil.date(), true);
            if (currentHour >= deadLineTime) {
                return CommonResult.failed("补卡超过第二天15点！");
            }
        }
        // 获取当前的时间分钟
        String year = DateUtil.format(req.getDate(), DatePattern.NORM_YEAR_PATTERN);
        String month = DateUtil.format(req.getDate(), "MM");
        String day = DateUtil.format(req.getDate(), "dd");
        SitQuietlyClock sitQuietlyClock = new SitQuietlyClock();
        sitQuietlyClock.setUserId(req.getMemberId());
        sitQuietlyClock.setType(1);
        sitQuietlyClock.setStartTime(DateUtil.offsetMinute(DateUtil.date(), -req.getTimeInterval()));
        sitQuietlyClock.setEndTime(DateUtil.date());
        sitQuietlyClock.setDateNo(dateNo);
        sitQuietlyClock.setYear(year);
        sitQuietlyClock.setMonth(month);
        sitQuietlyClock.setDay(day);
        sitQuietlyClock.setSignDate(DateUtil.format(req.getDate(), DatePattern.NORM_DATE_PATTERN));
        sitQuietlyClock.setTimeInterval(req.getTimeInterval());
        sitQuietlyClock.setDelFlag(DelFlagEnums.UNDELETED.getNo());
        sitQuietlyClock.setModifyTime(DateUtil.date());
        sitQuietlyClock.setCreateTime(DateUtil.date());
        sitQuietlyClockMapper.insertSelective(sitQuietlyClock);
        return CommonResult.success(1);

    }

    @Override
    public CommonResult applyHoliday(AppletHolidayDTO req) {
        Long dateNo = Long.valueOf(DateUtil.format(req.getDate(), DatePattern.PURE_DATE_FORMATTER));
        Long nowDateNo = Long.valueOf(DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_FORMATTER));

        // 请假最大只能补昨天的请假
        long num = DateUtil.betweenDay(req.getDate(), DateUtil.date(), true);
        if (num > 1) {
            return CommonResult.failed("补请假只能补到昨天！");
        }
        SitQuietlyClockExample applyExample = new SitQuietlyClockExample();
        applyExample.createCriteria().andUserIdEqualTo(req.getMemberId()).
                andTypeEqualTo(1).andDateNoEqualTo(dateNo);
        long applyNum = sitQuietlyClockMapper.countByExample(applyExample);
        if (applyNum > 0) {
            return CommonResult.failed("该天已打卡！");
        }
        SitQuietlyClockExample countExample = new SitQuietlyClockExample();
        countExample.createCriteria().andUserIdEqualTo(req.getMemberId()).andTypeEqualTo(2).andDateNoEqualTo(dateNo);
        long signNum = sitQuietlyClockMapper.countByExample(countExample);
        if (signNum > 0) {
            return CommonResult.failed("该天已请假！");
        }
        SitQuietlyClockExample kuangExample = new SitQuietlyClockExample();
        kuangExample.createCriteria().andUserIdEqualTo(req.getMemberId()).andTypeEqualTo(3).andDateNoEqualTo(dateNo);
        long kuanNum = sitQuietlyClockMapper.countByExample(kuangExample);
        if (kuanNum > 0) {
            return CommonResult.failed("该天已旷卡！");
        }

        // 补昨天的卡，今天3点以后就不能补
        // 如果当前时间小于现在
        if (dateNo < nowDateNo) {
            // 判断当前时间是否 大于下午3点
            int currentHour = DateUtil.hour(DateUtil.date(), true);
            if (currentHour >= deadLineTime) {
                return CommonResult.failed("请假超过第二天15点！");
            }
        }
        // 获取当前的时间分钟
        String year = DateUtil.format(req.getDate(), DatePattern.NORM_YEAR_PATTERN);
        String month = DateUtil.format(req.getDate(), "MM");
        String day = DateUtil.format(req.getDate(), "dd");
        SitQuietlyClock sitQuietlyClock = new SitQuietlyClock();
        sitQuietlyClock.setUserId(req.getMemberId());
        sitQuietlyClock.setType(2);
        sitQuietlyClock.setStartTime(DateUtil.offsetMinute(DateUtil.date(), -req.getTimeInterval()));
        sitQuietlyClock.setEndTime(DateUtil.date());
        sitQuietlyClock.setDateNo(dateNo);
        sitQuietlyClock.setYear(year);
        sitQuietlyClock.setMonth(month);
        sitQuietlyClock.setDay(day);
        sitQuietlyClock.setSignDate(DateUtil.format(req.getDate(), DatePattern.NORM_DATE_PATTERN));
        sitQuietlyClock.setTimeInterval(req.getTimeInterval());
        sitQuietlyClock.setDelFlag(DelFlagEnums.UNDELETED.getNo());
        sitQuietlyClock.setModifyTime(DateUtil.date());
        sitQuietlyClock.setCreateTime(DateUtil.date());
        sitQuietlyClockMapper.insertSelective(sitQuietlyClock);
        return CommonResult.success(1);

    }

    @Override
    public AppletStatsVO statsClockData(Long userId) {
        AppletStatsVO res = new AppletStatsVO();
        res.setClockAll(0);
        res.setClockMonth(0);
        res.setClockToday(0);


        Integer clockAll = sitQuietlyClockMapper.clockAll(userId);
        res.setClockAll(clockAll);


        Calendar calendar = Calendar.getInstance();
        // 获取当前时间
        calendar.getTime();

        // 获取本月第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date firstDayOfMonth = calendar.getTime();
        Long firstDayOfMonthDateNO = Long.valueOf(DateUtil.format(firstDayOfMonth, DatePattern.PURE_DATE_FORMATTER));

        // 获取本月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date lastDayOfMonth = calendar.getTime();
        Long lastDayOfMonthDateNO = Long.valueOf(DateUtil.format(lastDayOfMonth, DatePattern.PURE_DATE_FORMATTER));

        //获取本月的
        Integer clockMonth = sitQuietlyClockMapper.clockMonth(userId, firstDayOfMonthDateNO, lastDayOfMonthDateNO);
        res.setClockMonth(clockMonth);

        Date today = new Date();
        calendar.setTime(today);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endTime = calendar.getTime();
        Long endTimeDateNO = Long.valueOf(DateUtil.format(endTime, DatePattern.PURE_DATE_FORMATTER));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startTime = calendar.getTime();
        Long startTimeDateNO = Long.valueOf(DateUtil.format(startTime, DatePattern.PURE_DATE_FORMATTER));
        Integer clockToday = sitQuietlyClockMapper.clockMonth(userId, startTimeDateNO, endTimeDateNO);
        res.setClockToday(clockToday);
        return res;

    }

    @Override
    public String clockDetail(AppletClockDetailDTO req) {
        String detail = "详情为无";
        Long dateNo = Long.valueOf(DateUtil.format(DateUtil.parse(req.getDate(), DatePattern.NORM_DATETIME_PATTERN), DatePattern.PURE_DATE_FORMATTER));
        SitQuietlyClockExample example = new SitQuietlyClockExample();
        example.createCriteria().andUserIdEqualTo(req.getMemberId()).andDateNoEqualTo(dateNo);
        List<SitQuietlyClock> sitQuietlyClocks = sitQuietlyClockMapper.selectByExample(example);
        if (CollectionUtil.isNotEmpty(sitQuietlyClocks)) {
            SitQuietlyClock sitQuietlyClock = sitQuietlyClocks.get(0);
            detail = "打卡类型:" + SitQuietlyClockFieldEnum.TYPE.of(sitQuietlyClock.getType()).getDesc() + ",时长:" + sitQuietlyClock.getTimeInterval() + "分钟";
        }
        return detail;
    }

    private static Integer WEEK = 2;

    @Override
    public List<AppletRankVO> rankList(AppletRankDTO req) {
        Long memberId = req.getMemberId();
        UmsMember umsMember = umsMemberService.getById(memberId);
        req.setSourceType(umsMember.getSourceType());

        Long startDateNo = 0L;
        Long endDateNo = 0L;
        if (1 == req.getType()) {
            Long nowDateNo = Long.valueOf(DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_FORMATTER));
            startDateNo = nowDateNo;
            endDateNo = nowDateNo;
        } else if (WEEK.equals(req.getType())) {
            // 获取本周的开始时间，默认为周一
            Date beginOfWeek = DateUtil.beginOfWeek(new Date());
            // 获取本周的结束时间，默认为周日
            Date endOfWeek = DateUtil.endOfWeek(new Date());
            startDateNo = Long.valueOf(DateUtil.format(beginOfWeek, DatePattern.PURE_DATE_FORMATTER));
            endDateNo = Long.valueOf(DateUtil.format(endOfWeek, DatePattern.PURE_DATE_FORMATTER));
        } else {
            // 获取本月第一天
            Date firstDayOfMonth = DateUtil.beginOfMonth(new Date());
            // 获取本月最后一天
            Date lastDayOfMonth = DateUtil.endOfMonth(new Date());
            startDateNo = Long.valueOf(DateUtil.format(firstDayOfMonth, DatePattern.PURE_DATE_FORMATTER));
            endDateNo = Long.valueOf(DateUtil.format(lastDayOfMonth, DatePattern.PURE_DATE_FORMATTER));
        }
        req.setStartDateNo(startDateNo);
        req.setEndDateNo(endDateNo);
        return sitQuietlyClockMapper.rankList(req);

    }

}
